<?php


namespace app\model;


use think\exception\ValidateException;
use think\Model;

class Boutcardorder extends Model
{
    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'bout_card_order';


    public function paymethod()
    {
        return $this->hasOne(Paymethod::class, 'id', 'pay_method_id');
    }


    public function add_order(array $orderInfo){
        $orderInfo['uniacid'] = uniacid();
        $orderInfo['create_time'] = time();
        $orderInfo['update_time'] = time();
        $orderInfo['status'] = 0;

        $goodsInfo = Goods::where(['id'=>$orderInfo['goods_id']])->find();
        $orderInfo['goods_name'] = $goodsInfo['name'];
        $orderInfo['valid_date'] = $goodsInfo['bout_card_date'];
        $orderInfo['available_times'] = $goodsInfo['bout_card_bout'];

        $goodsImage = GoodsImage::where(['goods_id'=>$orderInfo['goods_id']])->select()->toArray();
        $orderInfo['goods_image'] = $goodsImage[0]['image'] ?? '';
        $orderInfo['order_num_alias'] = 'C'.build_order_no();

        $boutCardInfo = self::create($orderInfo);
        $order_id = $boutCardInfo->id;
        return [
            'id' => $order_id,
            'order_id' => $order_id,
//            'subject' => $order['pay_subject'],
//            'name' => $order['shipping_name'],
            'pay_order_no' => $orderInfo['order_num_alias'],
            'pay_total' => $orderInfo['price'],
            'payment_code' => $orderInfo['payment_code'],
            'uid' => (int)$orderInfo['uid']
        ];
    }

    public static function cancel_order($orderId){
//        0:未支付，1:待使用，2:使用中，3:已使用,4:待退款，5:已退款,6:已取消
        $orderInfo = Boutcardorder::find($orderId);
        if(empty($orderId)){
            return 0;
        }

        $orderInfo = $orderInfo->toArray();
        if($orderInfo['status'] == 0) {
            $order['status'] = 6;
        }else if($orderInfo['status'] == 1) {
            $order['status'] = 4;

            //todo 发起退款
        }else{
            throw new ValidateException('订单不可取消');
        }

        $order['id'] = $orderId;
        $order['update_time'] = time();
        self::update($order);
    }

    public static function pay_order($data){
        $id = $data['id'];
        $update['id'] = $id;
        $paymentCode = $data['payment_code'];

        $paymethod = Paymethod::where(['code'=>$paymentCode])->find();
        if(!empty($paymethod)){
            $update['payment_code'] = $paymentCode;
            $update['pay_method_id'] = $paymethod->id;
        }

        $update['status'] = 1;

        Boutcardorder::update($update);
    }
}
